<template>
  <el-dialog v-if="load" title="批量打印" v-model="visible" append-to-body :close-on-click-modal="false" :z-index="2000" width="500px" @close="handleClose">
    <el-form label-position="top">
      <el-form-item label="选择打印文件">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="w-full" @change="handleCheckAllChange">全选</el-checkbox>
        <el-checkbox-group v-model="checkeds" @change="handleCheckedChange">
          <el-checkbox v-for="city in optionList" :key="city" :label="city">{{
            city
          }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">打 印</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus';
import { getLodop } from '@/utils/LodopFuncs'
import { resMessage } from '@/utils/res'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

const emit = defineEmits(['close', 'success'])

const checkAll = ref(true)
const isIndeterminate = ref(false)
const checkeds = ref(['开票合同', '送货清单', '发票文件'])
const optionList = ['开票合同', '送货清单', '发票文件']

const handleCheckAllChange = (val) => {
  checkeds.value = val ? optionList : []
  isIndeterminate.value = false
}
const handleCheckedChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === optionList.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < optionList.length
}

// 打开弹窗
const list = ref([])
const open = async (b_ids) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  checkAll.value = true
  handleCheckAllChange(true)
  const res = await api.print({ b_ids })
  resMessage({
    res,
    btnText: '继续打印',
    success: (data) => {
      list.value = [data.list]
      visible.value = true
    }
  }).then(data => {
    list.value = [data.list]
    visible.value = true
  })
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

const isPDF = (url) => url.substring(url.lastIndexOf('.') + 1).toLowerCase() === 'pdf'

// 提交
const submit = async () => {
  if (!checkeds.value.length) {
    ElMessage.error('请选择打印文件')
    return
  }
  const showLoading = () => loadings.submit = true
  const closeLoading = () => loadings.submit = false
  const LODOP = getLodop()
  if (!LODOP) return
  LODOP.SET_PRINT_PAGESIZE(1, 0, 0, "A4")
  LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", 'Full-Width')
  showLoading()
  const fields = []
  for (const form of list.value) {
    // 开票合同
    if (checkeds.value.length && checkeds.value.includes('开票合同')) {
      fields.push(...form.contract)
    }

    // 送货清单
    if (checkeds.value.length && checkeds.value.includes('送货清单')) {
      fields.push(...form.deliver)
    }

    // 发票文件
    if (checkeds.value.length && checkeds.value.includes('发票文件')) {
      fields.push(...form.invoice)
    }
  }
  for (const d of [...new Set(fields)]) {
    LODOP.NEWPAGEA()
    if (isPDF(d)) {
      LODOP.ADD_PRINT_PDF(20, 20, '210mm', '280mm', d.replace('https', 'http'))
    } else {
      const html = `
      <div style='width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;'>
        <img src="${d}" style='width: 100%;height: auto;max-width: 100%;max-height:100%' />
      </div>
      `
      LODOP.ADD_PRINT_HTM(20, 20, '210mm', '280mm', html)
    }
  }
  LODOP.PREVIEW()
  await new Promise(reslove => setTimeout(reslove, list.value.length * 1000))
  closeLoading()
}

defineExpose({ open })
</script>
